package handler

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"homeword1103/cache"
	"homeword1103/model"
	"strconv"
	"time"
)

func Add(c *gin.Context) {
	title := c.PostForm("title")
	content := c.PostForm("content")
	author := c.PostForm("author")
	data := model.Article{
		Title:   title,
		Content: content,
		Author:  author,
	}
	model.DB.Create(&data)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}
func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "2"))
	offset := (page - 1) * size
	var data []model.Article
	redis_key := "article_list" + strconv.Itoa(page)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		model.DB.Offset(offset).Limit(size).Find(&data)
		jsonData, _ := json.Marshal(data)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour)
	} else {
		json.Unmarshal([]byte(cacheData), &data)
	}
	var total int64
	model.DB.Table("articles").Count(&total)
	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "success",
		"data":  data,
		"total": total,
	})
	return
}
func Detail(c *gin.Context) {
	id, _ := strconv.Atoi(c.Query("id"))
	var data model.Article
	redis_key := "article_detail" + strconv.Itoa(id)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		model.DB.Where("id = ?", id).Find(&data)
		jsonData, _ := json.Marshal(data)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour)
	} else {
		json.Unmarshal([]byte(cacheData), &data)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "success",
		"data": data,
	})
	return
}
func Delete(c *gin.Context) {
	id, _ := strconv.Atoi(c.PostForm("id"))
	var data model.Article
	redis_key := "article_" + strconv.Itoa(id)
	model.DB.Where("id = ?", id).Delete(&data)
	cache.Rdb.Del(cache.Ctx, redis_key)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "删除成功",
	})
	return
}
